package com.weasel.weixin.mp;

import com.weasel.weixin.commons.accounts.Oauth2AccessTokenRequest;
import com.weasel.weixin.commons.menu.MenuRequest;
import com.weasel.weixin.commons.menu.MenuResponse;
import com.weasel.weixin.commons.menu.bean.Menu;
import com.weasel.weixin.commons.menu.builder.MenuBuilders;
import com.weasel.weixin.commons.menu.builder.ViewButtonBuilder;
import com.weasel.weixin.mp.builder.MpConfigBuilder;
import com.weasel.weixin.mp.config.MpConfig;
import com.weasel.weixin.mp.jetty.JettyServletLauncher;
import com.weasel.weixin.mp.request.MpMenuRequest;
import com.weasel.weixin.mp.servlet.Oauth2AccessTokenServlet;
import com.weasel.weixin.mp.servlet.Oauth2UserInfoServlet;
import com.weasel.weixin.mp.servlet.RefreshOauth2AccessTokenServlet;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**授权认证测试
 * 运行后，会在微信公众号生成一个"授权"按键，可以取消微信公众号再关注，然后点击"授权"按键测试
 * 点击"授权"按键后，服务器返回一个页面，在页面里可以获取页面授权后用户信息和刷信授权accessToken
 * Created by Dylan on 2015/9/28.
 */
public class Oauth2AccessTokenDemo {

    public  static void main(String [] agrs) throws IOException, ExecutionException {


        MpConfig config = MpConfigBuilder.fromXML("classpath:weixin-config.xml");
        MenuRequest request = new MpMenuRequest(config);

        String url = new Oauth2AccessTokenRequest(config).getOauth2AccessTokenURL(Oauth2AccessTokenRequest.SNSAPI_USERINFO_SCOPE, "123");

        Menu menu = MenuBuilders.create()
                                .button(new ViewButtonBuilder().name("授权")
                                                               .url(url)
                                )
                                .build();

        MenuResponse response = request.create(menu);

        JettyServletLauncher.listen(8080)
                            .addServletWithMapping(new Oauth2AccessTokenServlet(), "/oauth2")
                            .addServletWithMapping(new RefreshOauth2AccessTokenServlet(),"/refresh_oauth2")
                            .addServletWithMapping(new Oauth2UserInfoServlet(),"/oauth2_userinfo")
                            .launch();
    }
}
